<template>
  <div class="multiple-card-container sparepart-card-container">
    <!-- start 按钮组 -->
    <div class="btn-wrap" >
      <el-button
        @click="handleApplyPart"
        v-if="allowApplyPartOut"
        type="primary"
        size="mini"
        plain
      >{{$t('task.detail.components.applyStock1')}}</el-button>
      <el-button
        v-if="isExport"
        @click="exportEvent"
        type="primary"
        size="mini"
        plain
      >{{$t('common.base.export')}}</el-button>

      <template v-if="allowCreate">
        <el-button type="primary" size="mini" plain @click="openChoosePartDialog" v-if="!allowApplyPartOut">{{$t('task.detail.components.addSparePart')}}</el-button>

        <el-dropdown trigger="click" @command="handleDropdownCommand" v-else>
          <el-button type="primary" size="mini" plain>{{$t('task.detail.components.addSparePart')}}</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">{{$t('task.detail.components.justAddSparePart')}}</el-dropdown-item>
            <el-tooltip class="item" effect="dark" :content="$t('task.tip.addSparePartTip1')" placement="right-start">
              <el-dropdown-item command="2">{{$t('task.detail.components.addAndApplySparePart')}}</el-dropdown-item>
            </el-tooltip>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </div>
    <!-- end 按钮组 -->

    <!-- start 备件清单列表 -->
    <sparepart-card-list
      ref="sparepartCardList"
      :data="data"
      :columns="columns"
      :list-loading="listLoading"
      :part-config="partConfig"
      :allow-edit="allowEdit"
      :edit-unit-price="editUnitPrice"
      :config="config"
      @successReturn="getInventoryByCardId"
    />
    <!-- end 备件清单列表 -->

    <!-- start 选择备件弹窗 -->
    <choose-part-dialog
      ref="choosePartDialog"
      type="sparePart"
      :colums="partColumns"
      :part-config="partConfig"
      @submit="addPart"
      :card="card"
    />
    <!-- end 选择备件弹窗 -->
    
    <!-- start 出库申请弹窗 -->
    <spare-part-apply-dialog
      ref="sparepartApplyDialog"
      :fields="fields"
      :part-config="partConfig"
      :card="card"
      :task="task"
      :value="data"
    />
    <!-- end 出库申请弹窗 -->

  </div>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
/* components */
import SparepartCardList from './SparepartCardList';
import SparepartApplyDialog from './SparepartApplyDialog.vue';
import ChoosePartDialog from '@src/modules/task/editAllot/components/PartSeviceList/components/ChoosePartDialog.vue';
/* mixin */
import cardMixin from './../CardMixin.js';
/* util */
import _ from 'lodash';
/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
/* model */
import { PART_SERVICE_LIST_MAX_LENGTH } from '@src/model/const/Number';
import { PART_SERVICE_LIST_MAX_LENGTH_MESSAGE } from '@src/model/const/Alert';

export default {
  name: 'spare-part-card',
  mixins: [cardMixin],
  props: {
    // 是否是工单负责人
    isExecutor: {
      type: Boolean,
      default: false
    },
    // 是否是工单协同人
    isSynergies: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 备件清单列表数据
      data: [],
      // 当前租户备件配置
      partConfig: {}
    }
  },
  computed: {
    /** 
    * @description 可显示字段
    * 1.可用字段 enbled
    * 2.且 未隐藏
    */
    fields() {
      let f = this.card.fields.filter(field => field.enabled && !field.isHidden);

      // 服务项目 是否展示终端销售价和小计
      if(!this.serviceProviderShowPrice) {
        f = f.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'total')
      }

      return f;
    },
    /** 
    * @description 备件清单列表项
    */
    columns() {
      let fields = [
        ...this.fields,
        {
          displayName: this.$t('task.detail.components.appliedNum'),
          fieldName: 'applyNum',
          minWidth: '100px'
        },
        {
          displayName: this.$t('task.detail.components.issued'),
          fieldName: 'useNum',
          minWidth: '80px'
        },
        {
          displayName: this.$t('common.form.preview.sparepart.des8'),
          fieldName: 'usedNum',
          minWidth: '100px'
        },
        {
          displayName: this.$t('task.detail.components.returnedQuantity'),
          fieldName: 'returnNum',
          minWidth: '100px'
        }
      ]

      // 是否有删除权限
      if (this.allowDelete) {
        fields.push({
          displayName: this.$t('common.base.operation'),
          fieldName: 'action',
          minWidth: '100px'
        })
      }

      // 设置备件名称列宽
      fields.forEach(field => {
        if (field.fieldName == 'name') {
          field.minWidth = '120px';
        }
      })

      return fields;
    },
    /** 
    * @description 选择备件弹窗列表项
    */
    partColumns() {
      let fields = [
        ...this.fields,
        {
          fieldName: 'action',
          displayName: this.$t('common.base.operation')
        }
      ]

      // 设置备件名称、预计用量列宽
      fields.forEach(field => {
        if (field.fieldName == 'name') {
          field.width = '160px';
        } else if (field.fieldName == 'preNum') {
          field.width = '100px';
        }
      })

      return fields;
    },
    /** 
    * @description 备件清单附加组件配置
    */
    config() {
      return JSON.parse(this.card.config || '{}');
    },
    /** 
    * @description 允许发起出库申请
    * 1. 开启了「 允许在工单中发起出库申请 」
    * 2. 且 登录账号是否是被允许使用的角色（工单负责人或协同人）
    */
    allowApplyPartOut() {
      let { isTaskOutRep, roleList = [] } = this.config;

      // 判断登录账号是否是被允许使用的角色
      let hasAuthRole = (this.isExecutor && roleList.includes('taskPrincipalPerson')) || (this.isSynergies && roleList.includes('taskSynergyPerson'));

      return isTaskOutRep && hasAuthRole;
    }
  },
  mounted() {
    this.$eventBus.$on('task_receipt_update_sparepart_config', this.getPartConfig);

    this.getInventoryByCardId();
    this.getPartConfig();
  },
  beforeDestroy() {
    this.$eventBus.$off('task_receipt_update_sparepart_config', this.getPartConfig);
  },
  methods: {
    /** 
    * @description 查询备件清单列表数据
    */
    async getInventoryByCardId() {
      try {
        const params = {
          cardId: this.card.cardId,
          taskId: this.task.id
        }
        
        let res = await TaskApi.getInventoryByCardId(params);
        if (!res.success || !res.result) return;

        this.data = res.result || [];
        this.data.forEach(item => {
          item.sort = item.sparepartType; // 类别
        })

      } catch(err) {
        console.error('sparepart getInventoryByCardId err', err)
      }
    },
    // 获取当前租户的备件配置
    async getPartConfig() {
      try {
        let res = await TaskApi.sparepartConfig();
        if (res.success) this.partConfig = res.result;
      } catch(err) {
        console.error('get part config error:', err);
      }
    },
    handleDropdownCommand(command) {
      if (command == 1) return this.openChoosePartDialog();

      this.openPartApplyDialog(false);
    },
    openAddonsDialogAuto() {
      if(this.allowCreate) {
        this.openChoosePartDialog()
      }
    },
    /** 打开添加备件弹窗 */
    openChoosePartDialog() {
      this.$refs.choosePartDialog.open();
    },
    /** 添加备件 */
    addPart(data) {
      // 过滤掉空数据
      let selectedData = data.filter(item => item.id);
      if (selectedData.length == 0) return this.$platform.alert(this.$t('task.tip.addPartTip1'));

      // 是否超过最大限制
      let isOverLimit = this.data.length + selectedData.length > PART_SERVICE_LIST_MAX_LENGTH;
      if (isOverLimit) return this.$platform.alert(PART_SERVICE_LIST_MAX_LENGTH_MESSAGE);

      this.$refs.choosePartDialog.togglePending(true);

      let baseTaskInventories = [];
      selectedData.forEach(item => {
        baseTaskInventories.push({
          taskId: this.task.id,
          taskNo: this.task.taskNo,
          cardId: this.card.cardId,
          relationId: item.id,
          relationName: item.name,
          preNum: item.preNum,
          salePrice: item.salePrice || 0,
          type: 1
        })
      })

      TaskApi.addTaskInventory({ baseTaskTypeId: this.task.templateId, baseTaskInventories })
        .then(res => {
          if (res.success) {
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.tip.addSuccess')
            })
            
            this.getInventoryByCardId();
            this.$refs.choosePartDialog.close();

            this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord);
          } else {
            this.$platform.alert(res.message);
            this.$refs.choosePartDialog.togglePending();
          }
        })
        .catch(err => {
          this.$refs.choosePartDialog.togglePending();
        })
    },
    /** 打开出库申请弹窗 */
    openPartApplyDialog(isOnlyPartOut = true, data = []) {
      this.$refs.sparepartApplyDialog.open(isOnlyPartOut, data);
    },
    handleApplyPart() {
      let { multipleSelection = [] } = this.$refs.sparepartCardList || {};
      if (multipleSelection.length == 0) return this.$platform.alert(this.$t('common.form.tip.sparepart.tips1'));

      this.openPartApplyDialog(true, _.cloneDeep(multipleSelection));
    }
  },
  components: {
    [SparepartApplyDialog.name]: SparepartApplyDialog,
    [SparepartCardList.name]: SparepartCardList,
    [ChoosePartDialog.name]: ChoosePartDialog
  }
}
</script>

<style lang="scss" scoped>
.sparepart-card-container {
  .el-dropdown {
    margin-left: 12px;
  }
}

.el-dropdown-menu {
  width: 125px;
}
</style>